// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
var app = angular.module('app', ['ionic', 'ngCordova', 'angularValidateWithToast', 'ionic-toast',
  'app.controllers', 'app.controllers-hotel', 'app.controllers-auxiliaryPolice',
  'app.routes', 'app.services', 'app.directives', 'app.config', 'app.controllers-police',
  // 3rd party dependencies
  'btford.socket-io','ionicLazyLoad'
]);


app.config(function ($httpProvider) {
  // delete header from client:
  // http://stackoverflow.com/questions/17289195/angularjs-post-data-to-external-rest-api
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];

  this.$inject = ['Storage'];
  this.$inject = ['$q'];
  /**
   * 拦截HttpProvider实现全局loading提示
   */
  $httpProvider.interceptors.push(function ($rootScope, Storage, $q) {

    return {
      request: function (config) {
        //TODO 实现全局的登陆拦截
        if (config.url.indexOf('api/v') != -1) {
          var token = Storage.getUserToken();
          config.url = URI(config.url).addSearch({'accessToken': token.accessToken}).addSearch({'tokenSecret': token.tokenSecret}).toString();
          if (config.url.indexOf('base/initData') == -1) {
            $rootScope.$broadcast('loading:show')
          }
        }
        return config
      },
      response: function (response) {
        //TODO  实现全局响应拦截
        if (response.config.url.indexOf('api/v') != -1) {
          $rootScope.$broadcast('loading:hide');
        }
        if (response.config.url.indexOf('api/v') != -1) {
        //  console.log("::::::response:" + angular.toJson(response.data));
        }

        return response
      },
      // This is the responseError interceptor
      responseError: function (rejection) {
        $rootScope.$broadcast('loading:hide');

        if (rejection.status === 401) {
          $rootScope.$broadcast('loginError401')
          return;
        }
        /* If not a 401, do nothing with this error.
         * This is necessary to make a `responseError`
         * interceptor a no-op. */
        return $q.reject(rejection);
      }
    }
  })
});

app.run(['$ionicPlatform', '$rootScope', '$ionicNavBarDelegate', '$ionicLoading', '$state', '$cordovaToast',  'Storage',
  '$timeout','$location','$ionicHistory',
  function ($ionicPlatform, $rootScope, $ionicNavBarDelegate, $ionicLoading, $state, $cordovaToast, Storage,
            $timeout,$location,$ionicHistory) {


    $ionicPlatform.ready(function () {


      /**
       * 需要打开KeyboardAccessoryBar的界面
       * @type {Array}
       */
      $rootScope.needKeyboardAccessoryBarStates = [
        'signUp',
        'auxiliaryPoliceRecordPerson',
        'auxiliaryPoliceRecordVehicle',
        'auxiliaryPoliceRecordGoods',
        'auxiliaryPoliceRecordEvent',
      ];

      /**
       *
       */
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        cordova.plugins.Keyboard.disableScroll(true);
      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
    });
    //双击退出
    $ionicPlatform.registerBackButtonAction(function (e) {
      //判断处于哪个页面时双击退出
      if ($location.path() == '/menu' || $location.path() == '/signIn') {
        if ($rootScope.backButtonPressedOnceToExit) {
          ionic.Platform.exitApp();
        } else {
          $rootScope.backButtonPressedOnceToExit = true;
          $cordovaToast.showShortCenter('再按一次退出系统');
          setTimeout(function () {
            $rootScope.backButtonPressedOnceToExit = false;
          }, 2000);
        }
      }
      else if ($ionicHistory.backView()) {
        $ionicHistory.goBack();
      } else {
        $rootScope.backButtonPressedOnceToExit = true;
        $cordovaToast.showShortCenter('再按一次退出系统');
        setTimeout(function () {
          $rootScope.backButtonPressedOnceToExit = false;
        }, 2000);
      }
      e.preventDefault();
      return false;
    }, 101);
    /**
     * 监听ui-router state实现对signIn隐藏返回键
     */
    $rootScope.$on('$stateChangeStart',
      function (event, toState, toParams, fromState, fromParams, options) {
        if (toState.url.indexOf('signIn') != -1 || toState.url.indexOf('menu') != -1) {
          $ionicNavBarDelegate.showBackButton(false);
        }
        else {
          $ionicNavBarDelegate.showBackButton(true);
        }
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard && $rootScope.needKeyboardAccessoryBarStates) {
          var isKeyboardAccessoryBar = false;
          for (var idx = 0; idx < $rootScope.needKeyboardAccessoryBarStates.length; idx++) {
            var itemState = $rootScope.needKeyboardAccessoryBarStates[idx];
            if (toState.name == itemState) {
              isKeyboardAccessoryBar = true;
              break;
            }
          }
          if (isKeyboardAccessoryBar) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
          } else {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
          }
        }

        if (toState.name.indexOf('hotel') != -1 && toState.name != 'hotelNotApprovedTip' && $rootScope.hotelStatus != 'approved') {
          event.preventDefault();// 取消默认跳转行为
          console.log("go hotelNotApprovedTip....");
          $state.go("hotelNotApprovedTip",{reload:true});
        }


      });

    $rootScope.$on('loading:show', function () {
      $ionicLoading.show({
        template: 'Loading...',
        noBackdrop: true
      })
    })

    $rootScope.$on('loading:hide', function () {
      $ionicLoading.hide()
    })
    $rootScope.$on('loginError401', function () {
      $ionicLoading.hide()
      $cordovaToast.showShortCenter("密码过期,请重新登陆!");
      $state.go('notifycation', {}, {reload: true});
    })

    //
    //socket.on('disconnect', function (data) {
    //  console.log("disconnect:" + data)
    //  //广播事件
    //  $rootScope.$broadcast('socketDisconnect');
    //
    //  console.log('App.run:已经与服务器断开了连接!!!!');
    //});
    //socket.on('welcome', function (data) {
    //  console.log('App.run:收到服务器的消息:' + data);
    //});
    //
    //// console.log('check 1', socket.getConnectStatus());
    //
    //socket.on('connect', function () {
    //  $rootScope.$broadcast('socketConnect');
    //
    //  console.log("App.run:已经连接到服务器,client.id" + socket.id + " +....");
    //
    //  var userToken = Storage.getUserToken();
    //  socket.emit('initEvent', {accessToken: userToken.accessToken, tokenSecret: userToken.tokenSecret});
    //});

  }]);
